package engine.newUi 
{
	import engine.data.BindManage;
	import engine.data.ModelLocator;
	import engine.data.RoleVo;
	import engine.event.SceneEvent;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.tip.TipsMainLogic;
	import engine.ui.lite.BaseUI;
	
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	
	import newx.com.ResManager;
	import newx.com.config.StaticIni;
	import newx.com.control.NxClip;
	import newx.com.control.Scroll.NxScrollPanel;
	import newx.com.control.Scroll.ScrollPolicy;
	import newx.com.control.button.NxButton;
	import newx.com.control.group.NxViewGroup;
	import newx.com.control.text.NxLabel;
	import newx.com.control.window.NxWindowEvent;

	
	/**
	 * ...
	 * @author GaoYQ
	 */
	public class ActivitiesUI extends BaseUI 
	{
		private static var _model			:ModelLocator;
		/***对象自己**/
		private static var _self	:ActivitiesUI;
		/**所有活动数组*/
		private var allListArr:Array = [];
		/**需要被显示的活动列表***/
		public var showListArr:Array = [];
		public var bg:MovieClip;
		/**服务器数据*/
		private var serviceArr:Array = [];
		private	var	_bindManage			:BindManage;
	
		public  var imgContainer:NxScrollPanel;
		public 	 var lab_info:NxLabel;
		public  var bgdi:MovieClip;

		/**绑定索引**/
		private var _statusIndex:int = -1;
		
		private var _levelIndex:int = -1;
		/**替身娃娃状态***/
		private var _activityStatusObj:Object = {};
		/**开启关闭状态**/
		private var _activityOpenObj:Object = {};
		/**记录活动数据**/
		private var _activityData:Object = {};
		/**活动列表**/
		private var _activiList:Array = [];
		/**绑定索引**/
		private var _bindIndex:int = -1;
		/**绑定索引**/
		private var _bindvipIndex:int = -1;
		/***列表数据**/
		private var activiList:Array = [];
		
		private var _bindLevelIndex:int;
		public function ActivitiesUI(popupUI:Boolean=true) 
		{
			super(popupUI);
		}
		
		public static function getInstance():ActivitiesUI
		{
			if(_self == null)
			{
				_self	=	new ActivitiesUI();		
			} 
			return _self
		}
		 
		
		override public function Init():void
		{
			_activiList = StaticIni.getIniVar("allAction","list").split(",");
			lab_info.visible = false;
//			imgContainer.addView(viewgroup_List);
			imgContainer.horizontalScrollPolicy = ScrollPolicy.OFF;
			imgContainer.verticalScrollPolicy = ScrollPolicy.AUTO;
			imgContainer.vscroll = 0;
			imgContainer.hscroll = 0;
			_model = ModelLocator.getInstance();

			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ACTIVITY_STATE), onShowdata);
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ACTIVITY_SCPEGOST_STATE), onShowdata);
			_bindLevelIndex = BindManage.getInstance().BindProp(_model.scene.Role,"Level",this,"levelChanged");
			BindManage.getInstance().BindProp(_model.scene.Role,"VIPLevel",this,"vipLevelChange");
		}
		
		public function set levelChanged(nowLevel:int):void
		{
//			if(nowLevel == 27)
//			{
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_UPDATE_ACTIVITY_STATE);//开启替身娃娃
			BindManage.getInstance().UnbindProp(_model.scene.Role,"Level",_bindLevelIndex);
//			}
		}
		
		
		public function set vipLevelChange(value:int):void
		{
			for(var i:int = 0;i<activiList.length;i++)
			{
				updataView(activiList[i]);
			}
		}

		private function checkItem(id:String):MovieClip
		{
			for(var i:int = 0;i<showListArr.length;i++)
			{
				if(showListArr[i]["Data"]["id"] == id)
				{
					return showListArr[i];
				}
			}
			return null;
		}

		public function checkAfk(id:int):int
		{
			var arr:Array = _model.scene.GetRecordEx("Scapegoat").recArr;
			for(var i:int = 0;i < arr.length;i++)
			{
				if(arr[i][0] == id)
					return arr[i][2];
			}
			return 0;
		}
		
		private function onShowdata(e:CustomMsgEvent):void
		{
			serviceArr 					     = e.pList;
			var state					:int = serviceArr[0]; //是否创建新的活动0.关闭，1开启。2.结束
			var id						:int = serviceArr[1]; //活动ID
			var style					:int = serviceArr[2];//活动类型2：全天3：定时
			//			var isOver					:int = serviceArr[3];//活动是否结束  0没结束。1结束
			//	var isContain				:int= sendIdArr.indexOf(id);//过滤服务器重复发送同一消息
			var status					:int = checkAfk(id);//serviceArr[3];//是否在替身娃娃中 0.不在。1在
			var isVip					:int = _model.scene.Role.GetProperties("VIPLevel")//(new RoleVo()).getPlayerLevel();
			var obj:Object = {};
			obj.id = id;
			obj.state = state;
			obj.style = style;
			obj.status = status;
			obj.isVip = isVip;
			_activityOpenObj[id] = state;
			_activityData [id] = obj;
			var isinlist:Boolean = false;
			if(_activiList.indexOf("action_"+id) == -1)return;
			for(var i:int = 0;i<activiList.length;i++)
			{
				if(activiList[i].id == id)
				{
					activiList[i] = obj;
					isinlist = true;
					break;
				}
			}
			if(!isinlist)
			{
				activiList.push(obj);
			}
			updataView(obj);
		}

		private function updataView(activitydata:Object):void
		{
			var state					:int = activitydata.state; //是否创建新的活动0.关闭，1开启。2.结束
			var id						:int = activitydata.id; //活动ID
			var style					:int = activitydata.style;//活动类型2：全天3：定时
			var status					:int = activitydata.status;
			var isVip					:int = _model.scene.Role.GetProperties("VIPLevel")//activitydata.isVip;
				
//			serviceArr 					     = e.pList;
//			var state					:int = serviceArr[0]; //是否创建新的活动0.关闭，1开启。2.结束
//			var id						:int = serviceArr[1]; //活动ID
//			var style					:int = serviceArr[2];//活动类型2：全天3：定时
////			var isOver					:int = serviceArr[3];//活动是否结束  0没结束。1结束
//		//	var isContain				:int= sendIdArr.indexOf(id);//过滤服务器重复发送同一消息
//			var status					:int = checkAfk(id);//serviceArr[3];//是否在替身娃娃中 0.不在。1在
//			var isVip					:int = _model.scene.Role.GetProperties("VIPLevel")//(new RoleVo()).getPlayerLevel();
//			var obj:Object = {};
//			obj.id = id;
//			obj.state = state;
//			obj.style = style;
//			obj.status = status;
//			obj.isVip = isVip;
//			_activityOpenObj[id] = state;
//			_activityData [id] = obj;
			var mc:MovieClip = checkItem(String(id)) as MovieClip;
//			if(id == 1)return;
			
			var itemObj:Object		= StaticIni.getIniObj("action_"+id) ;
			var level:int = _model.scene.Role.getPlayerLevel();
			if(level < int(itemObj.Level))return;
			if(mc == null)
			{
				mc = ResManager.newResClass("Castle_Item_22") as MovieClip;

//				mc = viewgroup_List.getChildAt(viewgroup_List.row-1) as MovieClip;
				
				addLevBtn(mc);
				showListArr.push(mc);
				displayActivityList(id.toString(),mc);
			}

			var o:Object = mc["Data"];
//
			mc["Data"]["id"] = id;
			mc["Data"]["state"] = state;
			mc["Data"]["style"] = style;
			var count:int = mc.numChildren;
			var statuLab:NxLabel = mc.getChildAt(count - 4) as NxLabel;
			var btn:NxButton = mc.getChildAt(count - 3) as NxButton;
			var lab:NxLabel  = mc.getChildAt(count - 2) as NxLabel;
			var checkBox:MovieClip = mc.getChildAt(count - 1) as MovieClip;
			
			
			if (state == 1 )
			{//开启
				btn.visible = true;
				checkBox.visible = true;
				statuLab.visible = false;
				checkBox.enabled = checkBox.mouseChildren = checkBox.mouseEnabled =  false;
				lab.visible = true;
				if(status == 1)
				{//替身娃娃中
					btn.enabled = false;
					checkBox.gotoAndStop(2);
					checkBox.enabled = checkBox.mouseChildren = checkBox.mouseEnabled =  true;
					lab.htmlStr = StaticIni.getSwfLangStr("UIString_1000130");
				}else
				{
					btn.enabled = true;
					checkBox.gotoAndStop(1);
					checkBox.enabled = checkBox.mouseChildren = checkBox.mouseEnabled =  false;
					lab.htmlStr = StaticIni.getSwfLangStr("UIString_1000129");
					btn.label = StaticIni.getSwfLangStr("UIStr_1001750") ;
				}
				if(mc["Data"]["itemPic"]["effect1"] != null){
					mc["Data"]["itemPic"]["effect1"].visible = true;
					mc["Data"]["itemPic"]["effect1"].play();
				}
			}
			else if(state == 0)
			{//关闭
				btn.visible = false;
				checkBox.visible = true;
				checkBox.enabled = checkBox.mouseChildren = checkBox.mouseEnabled = true;
				lab.htmlStr = StaticIni.getSwfLangStr("UIString_1000129");
				lab.visible = true;
				statuLab.visible = true;
				statuLab.htmlStr = StaticIni.getSwfLangStr("UIString_1000127");
				if(status == 1)
				{//替身娃娃中
					checkBox.gotoAndStop(2);
				}else
				{
					checkBox.gotoAndStop(1);
				}
				if(id == 13)
				{
					btn.visible = true;
					checkBox.visible = false;
					lab.visible = false;
					statuLab.visible = false;
					btn.label = StaticIni.getSwfLangStr("UIString_1000266") ;
				}
				if(mc["Data"]["itemPic"]["effect1"] != null){
					mc["Data"]["itemPic"]["effect1"].visible = false;
					mc["Data"]["itemPic"]["effect1"].stop();
				}
			}
			else
			{//结束
				btn.visible = false;
				checkBox.visible = true;
				checkBox.enabled = checkBox.mouseChildren = checkBox.mouseEnabled = true;
				lab.htmlStr = StaticIni.getSwfLangStr("UIString_1000129");
				lab.visible = true;
				statuLab.visible = true;
				statuLab.htmlStr = StaticIni.getSwfLangStr("UIString_1000128");
				if(status == 1)
				{//替身娃娃中
					checkBox.gotoAndStop(2);
				}else
				{
					checkBox.gotoAndStop(1);
				}
				
				if(id == 13)
				{
					btn.visible = true;
					checkBox.visible = false;
					lab.visible = false;
					statuLab.visible = false;
					btn.label = StaticIni.getSwfLangStr("UIString_1000368");
				}
				if(mc["Data"]["itemPic"]["effect1"] != null){
					mc["Data"]["itemPic"]["effect1"].visible = false;
					mc["Data"]["itemPic"]["effect1"].stop();
				}
			}
			//活动本身能不能使用替身娃娃功能
		   	var isShowAfk:int = int( StaticIni.getIniVar("action_"+id,"isShowAFK"));
			if(isVip < 5 || isShowAfk == 0)
			{//是不是VIP
				checkBox.visible = false;
				lab.visible = false;
			}else
			{
				checkBox.visible = true;
				lab.visible = true
			}
			setEffect();
		} 
		
		/**
		 *显示或者移除特效 
		 * 
		 */
		public function setEffect():void
		{
			for(var i:int = 0;i<showListArr.length;i++)
			{
				if(showListArr[i]["Data"]["state"] == "1")
				{
					ActivitesGroupLogic.getInstance().addEffect(1);
					return ;
				}
				ActivitesGroupLogic.getInstance().removeEffect(1);
			}
		}
		
		
		/***获取所有活动列表**/
		public  function getActiviList():void
		{
			var listStr:String = StaticIni.getIniObj("allAction")["list"];
			allListArr = listStr.split(",");
		}
	
		
		/**
		 *给NxviewGroup添加参加按纽 
		 * @param viewItem
		 * 
		 */
		private function addLevBtn(viewItem:MovieClip):void
		{
			var statusLab:NxLabel = new NxLabel();
			statusLab.text = StaticIni.getSwfLangStr("UIString_1000127");
			statusLab.x = 300;
			statusLab.y = 35;
			
			var leve:NxButton = new  NxButton();
			leve.label = StaticIni.getSwfLangStr("UIString_1000126");
			leve.width = 50;
			leve.height = 26;
			leve.x = 300;
			leve.y = 25;
			leve.skin = "Button_20";
			leve.	addEventListener(MouseEvent.CLICK,viewGroupout);
			
			var lab:NxLabel = new NxLabel();
			lab.text = StaticIni.getSwfLangStr("UIString_1000129");
			lab.x = 290;
			lab.y = 53;
			lab.	addEventListener(MouseEvent.MOUSE_OVER,babyOverHandle);
			lab.	addEventListener(MouseEvent.MOUSE_OUT,babyOutHandle);
			
			
			var checkBox:MovieClip = new MovieClip(); 
			checkBox = ResManager.newResClass("custSkin_13") as MovieClip;
			checkBox.x = 350;
			checkBox.y = 55;
			checkBox.buttonMode = true;
			checkBox.gotoAndStop(1);
			checkBox.	addEventListener(MouseEvent.CLICK,checkBoxClickHandle);
			checkBox.	addEventListener(MouseEvent.MOUSE_OVER,babyOverHandle);
			checkBox.	addEventListener(MouseEvent.MOUSE_OUT,babyOutHandle);
			viewItem.addChild(statusLab);
			viewItem.addChild(leve);
			viewItem.addChild(lab);
			viewItem.addChild(checkBox);
			viewItem["checkBox"] = checkBox;
		}
		
		private function babyOverHandle(e:MouseEvent):void
		{
			var dataArr:Array = _model.scene.GetRecordEx("ScapegoatComsumeNotes").recArr;
			var item:MovieClip = e.currentTarget.parent as MovieClip;
			var id:int = item["Data"]["id"];
			for(var i:int = 0;i<dataArr.length;i++)
			{
				if(dataArr[i][0] == id)
				{
					if(dataArr[i][1]== 0 && dataArr[i][2] == 0)
					{
						TipsMainLogic.instance.showMain(StaticIni.getSwfLangStrVar("BaiShiTipsStr_15",[StaticIni.getSwfLangStr("ActivityStr_"+id)]));
					}else
					{
						TipsMainLogic.instance.showMain(StaticIni.getSwfLangStrVar("BaiShiTipsStr_16",[StaticIni.getSwfLangStr("ActivityStr_"+id),dataArr[i][1],dataArr[i][2]]));
					}
					return;
				}
			}
		}
		
		private function babyOutHandle(e:MouseEvent):void
		{
			TipsMainLogic.instance.hide();
		}
		
		
		private function checkBoxClickHandle(e:MouseEvent):void
		{
			var sceneID:String 					= e.currentTarget.parent.Data["transition"];
			var id:String = e.currentTarget.parent.Data["id"];
			var style:String  =  e.currentTarget.parent.Data["style"]; 
			var mc:MovieClip = e.currentTarget as MovieClip;
			if(mc.currentFrame == 1)
			{
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_CHANGE_SCAPEGOAT_STATE,int(id),1);//开启替身娃娃

			}else
			{
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_CHANGE_SCAPEGOAT_STATE,int(id),0);//关闭替身娃娃

			}
		}
		
		/**
		 *参加按纽事件 a
		 * @param e
		 * 
		 */
		private function viewGroupout(e:MouseEvent):void
		{
			var sceneID:String 					= e.currentTarget.parent.Data["transition"];
			var id:String = e.currentTarget.parent.Data["id"];
			if (id == "3")
			{//战场特殊处理
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_JOIN_BF_REQUEST,0);//服务器发送场景ID
			}else if(id == "8")
			{//活动竞技特殊处理
				//参加活动竞技场
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_JOIN_ACTIVITY_COMPETE);
			}
			else if(id == "4" || id == "32")
			{//两个   世界Boss
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_WORLD_BOSS_PLAYER_ENTRY,int (id));
			}
			else {
				SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_SCENE_TRANSFER_REQUEST,sceneID);//服务器发送场景ID
			}
			
		}
		
		private function sortList():void
		{
			mcList.sortOn("index",Array.NUMERIC);
			//				function (left:int,right:int):int
			//			{
			//				if(left>right)
			//				{
			//					return 1;
			//				}
			//				return -1; 
			//			});
			var maxViewNum:int	=	showListArr.length;
			for(var i:int = 0;i<mcList.length;i++)
			{
				var mc:MovieClip = mcList[i]["mc"] as MovieClip;
				
				mc.y = 80 *i;
			}
			imgContainer.vscroll	= 0;
		}
		
		private var mcList:Array = [];
		/***显示活动**/
		private function displayActivityList(id:String,mc:MovieClip):void
		{
			
			//所要设定图片组的最大显示数
			var maxViewNum:int	=	showListArr.length;
			mc.y = mc.height *( maxViewNum-1);
			imgContainer.addView(mc);
			this.windowBG.width = 433;
			bgdi.width			 = 417;
			if (maxViewNum >= 4)
			{
				this.windowBG.height = 57 + mc.height * 4;
				imgContainer.viewHeight = 20 + mc.height * 4;
				lab_info.visible = false ;
			}else if (maxViewNum <= 0)
			{
				lab_info.visible = true;
				this.windowBG.height = 50 + mc.height * 1;
				imgContainer.viewHeight =  20 + mc.height * 1;
			}else
			{
				lab_info.visible = false;
				this.windowBG.width = 418;
				bgdi.width			 = 402;
				this.windowBG.height = 50 + mc.height * maxViewNum;
				imgContainer.viewHeight =  20 + mc.height * maxViewNum;
			}
			bgdi.height		=	this.windowBG.height	-	45;

			var itemObj:Object		= StaticIni.getIniObj("action_"+id) ;
			
			var iconPath		:String			=	itemObj["picName"];//图片地址
			var txtContent		:String			=	itemObj["description"];	//显示文本
			var transition			:String			=	itemObj["transition"];	//操作指令
			var enterLv		:int			=	int(itemObj["enterLv"]);//进入等级
			var viewItem:MovieClip	=	mc;//viewgroup_List.getItemByIndex(index) as MovieClip;
			
			var viewPic :NxClip		=	new NxClip();
			viewPic.x = 0;
			viewPic.y = 0;
			viewItem["Data"]					=	itemObj;
			viewItem["Data"]["id"] = id;
			
			var str:String = StaticIni.getSwfLangStr(txtContent);
			var titleFile:TextField  = viewItem.titleTxt as TextField;
			titleFile.width  = 300;
			titleFile.height = 100;
			titleFile.mouseEnabled =  false;
			
			if( null != str )
			{
				titleFile.htmlText = str;
			}

			var mc:MovieClip = ResManager.newResClass(iconPath) as MovieClip;
			mc.gotoAndStop(1);
			if(mc == null)return
			if(mc["effect1"] != null)
			{
				mc["effect1"].stop();
				mc["effect1"].visible	=	false;
			}
			viewPic.source = mc;
			viewItem.img2.addChild(viewPic);
			viewItem["Data"]["itemPic"] = mc;
			var eff:MovieClip =  ResManager.newResClass("custSkin_200") as MovieClip;
//			viewItem.img2.addChild(eff);
//			viewItem["eff"] = eff;
//			imgContainer.viewHeight = viewgroup_List.height;
//			imgContainer.viewHeight = mc.y+mc.height;
			mcList.push({id:id,index:itemObj.index,mc:viewItem});
		}
		

		/**
		 *  清空指定图片组
		 * @param viewGroupType 所要清空的图片组
		 * 
		 */		
		private function clearViewGroup(viewGroupType:NxViewGroup):void
		{
			//当前图片组最大显示数
			var maxNmu:int	=	viewGroupType.row * viewGroupType.col;
			for(var i:int = 0; i < maxNmu; i++)
			{
				var viewItem:MovieClip			=	viewGroupType.getItemByIndex(i) as MovieClip;
				viewItem. data					=	null;
				viewItem. titleTxt. htmlText	=	"";
				if(viewItem.numChildren>1)
				{
					viewItem.removeChildAt(viewItem.numChildren-1);
					viewItem.removeChildAt(viewItem.numChildren-1);
					viewItem.removeChildAt(viewItem.numChildren-1);
				}
				
				while(viewItem.img2.numChildren>0)
				{
					viewItem.img2.removeChildAt(0);
					viewItem["Data"]	=	null;
				}
			}
		}
		/**
		 *关闭界面 
		 * @param e
		 * 
		 */
		private function onClickClose(e:NxWindowEvent):void
		{
			removeListenter();
			this.showOrHide();			
		}
		
		/**
		 * 替身娃娃表变化
		 */	
		public function onaddPerHandle(PropertiesName:String,PropertiesValue:Array,data:*):void
		{
			var id :String = PropertiesValue[0].toString();
			
			var obj:Object = _activityData [id];
			if(obj!=null)
			{
				obj.status = PropertiesValue[2]
				updataView(obj);
			}
//			var mc:MovieClip = checkItem(String(PropertiesValue[0])) as MovieClip;
//			if(mc != null)
//			{
//				var count:int = mc.numChildren;
//				var checkBox:MovieClip = mc["checkBox"] as MovieClip;
//				
//				checkBox.gotoAndStop(PropertiesValue[2]+1);
//			}
		}
		
		/**
		 *在这里用不到 
		 */		
		public function onremovePerHandle(PropertiesName:String,PropertiesValue:Array,data:*):void
		{		
//			BindManage.getInstance().UnbindRecord("Scapegoat",_bindIndex);
		}
		
		/**
		 *添加监听 
		 * 
		 */
		private function addListenter():void
		{
			windowBG.addEventListener(NxWindowEvent.WINDOW_CLOSE,onClickClose);
		}
		
		
		/**
		 *移除监听 
		 * 
		 */
		private function removeListenter():void
		{
			windowBG.removeEventListener(NxWindowEvent.WINDOW_CLOSE,onClickClose);
			BindManage.getInstance().UnbindRecord("Scapegoat",_bindIndex);
			BindManage.getInstance().UnbindProp(_model.scene.Role,"VIPLevel",_bindvipIndex);
		}
		
		private function updataStatus():void
		{
		
		}
		
		public function set onVipLevelChenge(value:int):void 
		{
			BindManage.getInstance().UnbindRecord("Scapegoat",_bindIndex);
			_bindIndex = 	BindManage.getInstance().BindRecord(_model.scene,"Scapegoat",onaddPerHandle,onremovePerHandle);
		}
		
		override protected function BeforeShow():void
		{
			_bindIndex = 	BindManage.getInstance().BindRecord(_model.scene,"Scapegoat",onaddPerHandle,onremovePerHandle);
			_bindvipIndex = BindManage.getInstance().BindProp(_model.scene.Role,"VIPLevel",this,"onVipLevelChenge");
			if(showListArr.length < 1)
			{
				lab_info.visible = true;
				this.windowBG.height = 50 + 75 * 1;
				bgdi.height		=	this.windowBG.height	-	45;
			}
			imgContainer.viewHeight = 75 *( showListArr.length)+ 25;
			imgContainer.vscroll = 0;
			imgContainer.height = 320;
			imgContainer.viewWidth = 380;
			imgContainer.width = 380;
			addListenter();
			sortList();
			
		}
		
		override protected function AfterHide():void
		{
			removeListenter();
		}
		
	}

}